package com.deodar.system.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import com.deodar.system.domain.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * XML文件生成
 * @author zhaiyangyang
 *
 */
public class XMLGenerator_NB {
	private static Logger logger = LoggerFactory.getLogger(XMLGenerator_NB.class);
	private static final String TAG_PACKAGE = "Package";
	private static final String TAG_PACKAGE_HEAD = "PackageHead";
	private static final String TAG_SJBBH = "SJBBH";	
	private static final String TAG_SJBLX = "SJBLX";	
	private static final String TAG_DWDM = "DWDM";	
	private static final String TAG_DWMC = "DWMC";	
	private static final String TAG_JLS = "JLS";	
	private static final String TAG_INFODATE = "INFODATE";
	private static final String TAG_SJLX = "SJLX";
	private static final String TAG_DATA = "Data";
	private static final String TAG_RECORD = "Record";
	private static final String TAG_INDEX = "index";
	
	private String dwmc,dwdm;
	private String strEndDay, strNow ;
	private String xmlSavePath;
	
	private static final Pattern pattern = Pattern.compile("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\\x7f]");
	
	public XMLGenerator_NB(MLKContext context){
		dwmc = context.getDwmc();
		dwdm = context.getDwdm();
		strEndDay = context.getEndTime().substring(0,8);
		strNow = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		xmlSavePath = context.getXmlSavePath();
	}

	private void setText(Element ele, String name, String value) {
		if(value == null) {
			return ;
		}
		value = pattern.matcher(value).replaceAll("");
		ele.addElement(name).addCDATA(value);
	}
	
	/**
	 * 生成个各节点
	 * @param eleRecord
	 * @param annualReportInfo
	 */
	private void writeToXML(Element eleRecord, AnnualReportInfo annualReportInfo){
		//年报基本信息
		setText(eleRecord, "ANCHEDATE", annualReportInfo.getAnchedate());
		setText(eleRecord, "ANCHEYEAR", annualReportInfo.getAncheyear());
		setText(eleRecord, "REGNO", annualReportInfo.getRegno());
		setText(eleRecord, "UNISCID", annualReportInfo.getUniscid());
		setText(eleRecord, "ENTNAME", annualReportInfo.getEntname());
		setText(eleRecord, "TEL", annualReportInfo.getTel());
		setText(eleRecord, "ADDR", annualReportInfo.getAddr());
		setText(eleRecord, "POSTALCODE", annualReportInfo.getPostalcode());
		setText(eleRecord, "EMAIL", annualReportInfo.getEmail());
		setText(eleRecord, "BUSST", annualReportInfo.getBusst());
		setText(eleRecord, "EMPNUM", annualReportInfo.getEmpnum());
		//认缴信息
		List<SubscribedInfo> subscribeds = annualReportInfo.getSubscribeds();
		if (subscribeds.size() > 0) {
			Element element = eleRecord.addElement("SUBSCRIBEDINFOS");
			for (SubscribedInfo subscribed : subscribeds) {
				Element ele = element.addElement("SUBSCRIBEDINFO");
				setText(ele, "INV", subscribed.getInv());
				setText(ele, "LISUBCONAM", subscribed.getLisubconam());
				setText(ele, "CONDATE", subscribed.getCondate());
				setText(ele, "CONFORM", subscribed.getConform());
				setText(ele, "CURRENCY", subscribed.getCurrency());
			}
		}
		//实缴信息
		List<PaidInfo> paids = annualReportInfo.getPaids();
		if (paids.size() > 0) {
			Element element = eleRecord.addElement("PAIDINFOS");
			for (PaidInfo paid : paids) {
				Element ele = element.addElement("PAIDINFO");
				setText(ele, "INV", paid.getInv());
				setText(ele, "LIACCONAM", paid.getLiacconam());
				setText(ele, "CONDATE", paid.getCondate());
				setText(ele, "CONFORM", paid.getConform());
				setText(ele, "CURRENCY", paid.getCurrency());
				
			}
		}
		//对外投资信息
		List<InvesInfo> inves = annualReportInfo.getInves();
		if (inves.size() > 0) {
			Element element = eleRecord.addElement("INVESINFOS");
			for (InvesInfo inve : inves) {
				Element ele = element.addElement("INVESINFO");
				setText(ele, "HASINVESMSG", inve.getHasinvesmsg());
				setText(ele, "ENTNAME", inve.getEntname());
				setText(ele, "REGNO", inve.getRegno());
			}
		}
		//网站或网店信息
		List<WebsiteInfo> websites = annualReportInfo.getWebsites();
		if (websites.size() > 0) {
			Element element = eleRecord.addElement("WEBSITEINFOS");
			for (WebsiteInfo website : websites) {
				Element ele = element.addElement("WEBSITEINFO");
				setText(ele, "HASWEBSITE", website.getHaswebsite());
				setText(ele, "WEBTYPE", website.getWebtype());
				setText(ele, "WEBSITNAME", website.getWebsitname());
				setText(ele, "DOMAIN", website.getDomain());
			}
		}
		//股权变更信息
		List<EquityChangeInfo> equityChanges = annualReportInfo.getEquityChanges();
		if (equityChanges.size() > 0) {
			Element element = eleRecord.addElement("EQUITYCHANGEINFOS");
			for (EquityChangeInfo equityChange : equityChanges) {
				Element ele = element.addElement("EQUITYCHANGEINFO");
				setText(ele, "HASTRANSAM", equityChange.getHastransam());
				setText(ele, "INV", equityChange.getInv());
				setText(ele, "TRANSAMPR", equityChange.getTransampr());
				setText(ele, "TRANSPMPR", equityChange.getTranspmpr());
				setText(ele, "ALTDATE", equityChange.getAltdate());
			}
		}
		//企业资产状况
		AssetStatusInfo assetStatusInfo = annualReportInfo.getAssetStatusInfo();
		if(null != assetStatusInfo){
			Element element = eleRecord.addElement("ASSETSTATUSINFO");
			setText(element, "ASSGRO", assetStatusInfo.getAssgro());
			setText(element, "LIAGRO", assetStatusInfo.getLiagro());
			setText(element, "VENDINC", assetStatusInfo.getVendinc());
			setText(element, "MAIBUSINC", assetStatusInfo.getMaibusinc());
			setText(element, "PROGRO", assetStatusInfo.getProgro());
			setText(element, "NETINC", assetStatusInfo.getNetinc());
			setText(element, "RATGRO", assetStatusInfo.getRatgro());
			setText(element, "TOTEQU", assetStatusInfo.getTotequ());
		}
		//统计相关信息
		StatInfo statInfo = annualReportInfo.getStatInfo();
		if(null != statInfo){
			Element element = eleRecord.addElement("STATINFO");
			setText(element, "MAINBUSIACT", statInfo.getMainbusiact());
			setText(element, "WOMEMPNUM", statInfo.getWomempnum());
			setText(element, "HOLDINGSMSG", statInfo.getHoldingsmsg());
			setText(element, "UNISCID", statInfo.getUniscid());
		}
		//工商联络员信息
		LiaisonInfo liaisonInfo = annualReportInfo.getLiaisonInfo();
		if(null != liaisonInfo){
			Element element = eleRecord.addElement("LIAISONINFO");
			setText(element, "NAME", liaisonInfo.getName());
			setText(element, "MOBTEL", liaisonInfo.getMobtel());
		}
	}

	/**
	 * 生成XML文件
	 * @param baseinfos
	 * @param sjbbh
	 * @throws IOException
	 */
	public void generateXML(List<AnnualReportInfo> baseinfos,String sjbbh) throws IOException {
//		logger.debug("开始生成XML文件");
		File file = new File(xmlSavePath);
		if (!file.exists()) {
			if (!file.mkdirs()) {
				logger.error("创建xml文件目录失败:" + file.getAbsolutePath());
			}
		}
		Document document = DocumentHelper.createDocument();
		Element elePackage = document.addElement(TAG_PACKAGE);// 根节点

		// 写入头部信息
		Element elePackageHead = elePackage.addElement(TAG_PACKAGE_HEAD);
		// + getSeriaIndex();
		elePackageHead.addElement(TAG_SJBBH).setText(sjbbh + "");
		elePackageHead.addElement(TAG_SJBLX).setText("GSXX");
		elePackageHead.addElement(TAG_DWDM).setText(dwdm);
		elePackageHead.addElement(TAG_DWMC).setText(dwmc);
		elePackageHead.addElement(TAG_JLS).setText(baseinfos.size() + "");
		elePackageHead.addElement(TAG_INFODATE).setText(strNow);
		elePackageHead.addElement(TAG_SJLX).setText("NBXX");

		// 写入record
		Element eleData = elePackage.addElement(TAG_DATA);
		for (int i = 0; i < baseinfos.size(); i++) {
			AnnualReportInfo bean = baseinfos.get(i);
			Element eleRecord = eleData.addElement(TAG_RECORD);
			eleRecord.addAttribute(TAG_INDEX, (i + 1) + "");
			writeToXML(eleRecord, bean);
		}
		// 写到XML
		String logFileName = file.getAbsolutePath() + File.separator + "WZHY_GSXX_" + sjbbh + ".xml";
		FileOutputStream fos = new FileOutputStream(new File(logFileName));
		try {
			OutputStreamWriter writer = new OutputStreamWriter(fos, "gbk");
			try {
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("gbk");
				XMLWriter xwriter = new XMLWriter(writer, format);
				try {
					xwriter.setEscapeText(false);
					xwriter.write(document);
				} finally {
					xwriter.close();
				}
			} finally {
				writer.close();
			}
		} finally {
			fos.close();
		}
		logger.info("生成XML文件完毕:" + "WZHY_GSXX_" + sjbbh + ".xml");
	}

	public void waitForComplete() {

	}

	public void close() {

	}
}
